package com.jn.system.service.impl;

import com.jn.common.core.domain.AjaxResult;
import com.jn.system.service.IChunkFileService;
import com.jn.system.utils.file.ChunkFileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * 分片文件上传服务实现类
 */
@Service
public class ChunkFileServiceImpl implements IChunkFileService {
    private static final Logger log = LoggerFactory.getLogger(ChunkFileServiceImpl.class);

    @Autowired
    private Environment environment;


    // 服务器IP地址
    private String serverIp;
    // 服务器端口
    private String serverPort;


    @PostConstruct
    public void init() {
        // 获取服务器端口（从配置中读取）
        this.serverPort = environment.getProperty("server.port", "8080");
        // 获取服务器IP地址
        this.serverIp = getServerIp();
    }


    @Override
    public String getFileId(String fileName, Long fileSize, String fileType) {
        return ChunkFileUtils.generateFileId(fileName, fileSize, fileType);
    }

    @Override
    public AjaxResult uploadChunk(String fileId, Integer chunk, MultipartFile file) {
        try {
            boolean result = ChunkFileUtils.saveChunk(fileId, chunk, file);
            return result ? AjaxResult.success("分片上传成功") : AjaxResult.error("分片上传失败");
        } catch (Exception e) {
            log.error("分片上传异常", e);
            return AjaxResult.error("分片上传异常: " + e.getMessage());
        }
    }

    @Override
    public AjaxResult mergeChunks(String fileId, String fileName, Integer chunks) {
        try {
            String url = ChunkFileUtils.mergeChunks(fileId, fileName, chunks);
            String relativeUrl = "http://"+serverIp +":"+ serverPort + url;
            return AjaxResult.success()
                    .put("url", relativeUrl)
                    .put("fileName", fileName);
        } catch (Exception e) {
            log.error("文件合并异常", e);
            ChunkFileUtils.deleteChunkDir(fileId);
            return AjaxResult.error("文件合并失败: " + e.getMessage());
        }
    }

    @Override
    public AjaxResult cancelUpload(String fileId) {
        try {
            ChunkFileUtils.deleteChunkDir(fileId);
            return AjaxResult.success("已取消上传");
        } catch (Exception e) {
            log.error("取消上传异常", e);
            return AjaxResult.error("取消上传失败: " + e.getMessage());
        }
    }


    /**
     * 获取服务器有效IP地址（非回环地址、非虚拟地址）
     */
    private String getServerIp() {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface ni = interfaces.nextElement();
                Enumeration<InetAddress> addresses = ni.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress addr = addresses.nextElement();
                    // 排除回环地址和IPv6地址
                    if (!addr.isLoopbackAddress() && addr.isSiteLocalAddress()
                            && !addr.getHostAddress().contains(":")) {
                        return addr.getHostAddress();
                    }
                }
            }
            // 如果没有找到有效IP，返回本地地址
            return InetAddress.getLocalHost().getHostAddress();
        } catch (SocketException | UnknownHostException e) {
            log.error("获取服务器IP地址异常", e);
            return "127.0.0.1";
        }
    }
}
